package com.mmloo.manage.controller;

import com.mmloo.common.exception.MMLOOException;
import com.mmloo.common.model.User;
import com.mmloo.manage.service.LoginManageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by jessy on 2015/9/25.
 */
@Controller
@RequestMapping("/manage/")
public class LoginManageController {
    private Logger logger = LoggerFactory.getLogger(LoginManageController.class);

    @Autowired
    LoginManageService loginManageService;



    /**
     * 用户请求登录
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){

        logger.info("request for login page");
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            return "redirect:/manage/home";
        }
        return "login";
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @param request
     * @param model
     * @return
     * @throws MMLOOException
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(@RequestParam(value = "username")String username,
                        @RequestParam(value = "password")String password,
                        @RequestParam(value = "code")String loginKaptchaCode,
                        HttpServletRequest request,
                        Model model) throws MMLOOException {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()||subject.isRemembered()){
            return "redirect:/manage/home";
        }
        Session shiroSession = subject.getSession();
        Object kaptchaCode = shiroSession.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (kaptchaCode!=null && !StringUtils.equalsIgnoreCase(loginKaptchaCode, kaptchaCode.toString()))
        {
            model.addAttribute("message", "验证码错误!");/*米多奇雪饼500g 美食糕点非油炸食品 休闲零食批发 散装称重*/
            return "/login";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,false,request.getRemoteHost());
        try{
            subject.login(token);
            User user = loginManageService.findByUsername(username);
            request.getSession(true).setAttribute("loginUser",user);
            return "redirect:/manage/home";
        }catch (UnknownAccountException uae){
            logger.info("Unknown User!");
            model.addAttribute("message","Unknown User!");
        } catch (IncorrectCredentialsException ice)
        {
            logger.info("Incorrect Password!");
            model.addAttribute("message", "Incorrect Password!");

        } catch (LockedAccountException lae)
        {
            logger.info("User Locked!");
            model.addAttribute("message", "User Locked!");

        } catch (AuthenticationException ae)
        {
            logger.info("Authentication Failed!");
            model.addAttribute("message", "Authentication Failed!");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "login";
    }

    /**
     * 首页
     * @return
     */
    @RequestMapping(value = "home",method = RequestMethod.GET)
    public String home(){
        return "manage/goods/uploadPic";
    }

    /**
     * 注销登录
     * @return
     */
    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public String logout(HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        request.getSession(true).removeAttribute("loginUser");
        return "login";
    }

}
